import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PdfGenerator {

    public static void main(String[] args) throws Exception {
        List<Product> products = new ArrayList<>();
        products.add( new Product("烟花A", "璀璨夺目，五彩缤纷", "C:\\Users\\wy\\Pictures\\Screenshots\\屏幕截图 2025-01-25 224208.png"));
        products.add( new Product("烟花B", "浪漫之夜，星光点点", "C:\\Users\\wy\\Pictures\\Screenshots\\屏幕截图 2025-01-25 224208.png"));

        generatePdfFromTemplate("C:\\Users\\wy\\Desktop\\1.pdf", "C:\\Users\\wy\\Desktop\\2.pdf", products);
    }

    public static void generatePdfFromTemplate(String templatePath, String outputPath, List<Product> products) throws IOException {
        try (PDDocument outputDoc = new PDDocument()) {
            for (Product p : products) {
                // 打开模板页
                try (PDDocument templateDoc = PDDocument.load(new File(templatePath))) {
                    PDPage templatePage = templateDoc.getPage(0);

                    // 导入模板页作为新页
                    PDPage newPage = outputDoc.importPage(templatePage);

                    // 打开内容流
                    try (PDPageContentStream contentStream = new PDPageContentStream(outputDoc, newPage, PDPageContentStream.AppendMode.APPEND, true)) {

                        // 加载字体（支持中文）
                        PDType0Font font = PDType0Font.load(outputDoc, new File("C:/Windows/Fonts/simsun.ttc"));

                        // 写文字
                        contentStream.beginText();
                        contentStream.setFont(font, 16);
                        contentStream.newLineAtOffset(100, 500); // 文字位置（x,y）
                        contentStream.showText(p.name);
                        contentStream.endText();

                        contentStream.beginText();
                        contentStream.setFont(font, 12);
                        contentStream.newLineAtOffset(100, 470);
                        contentStream.showText(p.desc);
                        contentStream.endText();

                        // 加图片
                        PDImageXObject image = PDImageXObject.createFromFile(p.imagePath, outputDoc);
                        contentStream.drawImage(image, 350, 400, 150, 150); // 图片位置和大小
                    }
                }
            }

            outputDoc.save(outputPath);
        }
    }

    static class Product {
        String name;
        String desc;
        String imagePath;

        public Product(String name, String desc, String imagePath) {
            this.name = name;
            this.desc = desc;
            this.imagePath = imagePath;
        }
    }
}
